/*
 * Copyright (c) 2010 Virtium Technology,
 * All Rights Reserved.
 * This work contains trade secrets and confidential material of
 * Virtium Technology.
 *
 * Warning: Any unauthorised dissemination, disclosure or use of the content
 * in whole or in part without the explicit consent of Virtium technology
 * will be deemed as intellectual property infindgement and the
 * offender will be subjected to legal actions.
 *
 * Project  : VPC
 * Name   : FileUtil.java
 *
 */
package com.virtium.vpc.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;


/**
 * Provides File utility methods that can be used to perform common operations.
 * 
 * @author TuanAnh
 * @version
 * @since
 */

public class FileUtil {
	
	public static String virtiumServerPath;
	
	private static Logger log = Logger.getLogger(FileUtil.class);

	/**
	 * Read the contents from the file
	 * 
	 * @param filename
	 * @return
	 */
	public static String readFile(String filename) {
		StringBuffer sb = null;
		String nextLine = "";
		String lineSep;
		try {
			lineSep = System.getProperty("line.separator");
			BufferedReader br = new BufferedReader(new FileReader(filename));
			sb = new StringBuffer();
			while ((nextLine = br.readLine()) != null) {
				sb.append(nextLine);
				// note: BufferedReader strips the EOL character.
				sb.append(lineSep);
			}
		} catch (Throwable t) {
			log.error("Exception in readFile()", t);
		} finally {
			return sb.toString();
		}
	}

	/**
	 * Uploads file from client side to application server.
	 * <p>
	 * 
	 * @param formFile
	 *            FormFile to be uploaded
	 * @param outputFilePath
	 */
	public static boolean uploadFile(String folder, String newFilePath, byte[] fileData)
			throws Exception {
		
		try {
			// create new folder if not exist
			File curFolder = new File(folder);
			if (!curFolder.exists())curFolder.mkdir();
			
			// upload new file
			File dat = new File(newFilePath);
			FileOutputStream datStream = new FileOutputStream(dat);
			if (datStream != null) {
				datStream.write(fileData);
				datStream.flush();
				datStream.close();
			}
			return true;
		} catch (Exception e) {
			return false;
		}
		

	}
	
	// Deletes all files and subdirectories under dir.
	// Returns true if all deletions were successful.
	// If a deletion fails, the method stops attempting to delete and returns
	// false.
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}
	/**
	 * Renames the file name.
	 * <p>
	 * The system will first verify if there is a file with the given filename.
	 * <p>
	 * If yes, the system will override the existing file with the new file.
	 * 
	 * @param origFileName
	 * @param newFileName
	 * @return
	 */
	public static boolean renameFile(String origFileName, String newFileName) {
		log.debug("===== origFileName: " + origFileName);
		log.debug("===== newFileName: " + newFileName);

		boolean flag = false;

		try {
			if (!StringUtil.isEmpty(origFileName)
					&& !StringUtil.isEmpty(newFileName)) {

				File orgFile = new File(origFileName);
				File newFile = new File(newFileName);

				// check that the image already exists.
				// if yes, this file should be overwritten with the new one.
				if (newFile.exists()) {
					newFile.delete();
				}
				flag = orgFile.renameTo(newFile);

			}
		} catch (Exception e) {
			log.error("Exception while renaming file: " + e.getMessage()
					+ " - " + e.getClass().getName());
		}

		return flag;
	}

	/**
	 * Verifies if the file exists.
	 * <p>
	 * If not, system will create a new folder at the specified location.
	 * 
	 * @param fileName
	 * @param filePath
	 * @return
	 */
	public static boolean createFile(String filePath) {
		boolean flag = false;

		if (!StringUtil.isEmpty(filePath)) {

			// verify if the file exists. If not, create the folder.
			File file = new File(filePath);

			if (file.exists()) {
				log.debug("===== File exists.");
				flag = true;
			} else {
				flag = file.mkdir();
				log
						.debug("===== File does not exist. Creating the new folder: "
								+ flag);
			}
		}

		return flag;
	}

	public static boolean deleteFile(String filePath) {
		boolean flag = false;

		if (!StringUtil.isEmpty(filePath)) {

			// verify if the file exists. If not, create the folder.
			File file = new File(filePath);
			file.delete();
			if (!file.exists()) {
				log.debug("===== File exists.");
				flag = true;
			}
		}

		return flag;
	}
	
	public static boolean downloadFile(String filePath, String fileName,
			HttpServletResponse response) {

		System.out.println("===== In FileUtil, filePath: " + filePath);
		System.out.println("===== fileName: " + fileName);

		FileInputStream istr = null;
		OutputStream ostr = null;
		
		try {
			File fname = new File(filePath);
			if (fname != null) {

				// set for tif image
				if ((fname.getName().lastIndexOf(".tif") != -1)
						|| (fname.getName().lastIndexOf(".tiff") != -1)) {
					response.setContentType("image/tiff");
				}
				// set for gif image
				else if (fname.getName().lastIndexOf(".gif") != -1) {
					response.setContentType("image/gif");
				}
				// set for jpg image
				else if ((fname.getName().lastIndexOf(".jpg") != -1)
						|| (fname.getName().lastIndexOf(".jpeg") != -1)
						|| (fname.getName().lastIndexOf(".jpe") != -1)) {
					response.setContentType("image/jpeg");
				}
				// set for bmp image
				else if (fname.getName().lastIndexOf(".bmp") != -1) {
					response.setContentType("image/x-ms-bmp");
				}
				// set for png image
				else if (fname.getName().lastIndexOf(".png") != -1) {
					response.setContentType("image/x-png");
				}
				// set for pdf file
				else if (fname.getName().lastIndexOf(".pdf") != -1) {
					response.setContentType("application/pdf");
				}
				// set for word file
				else if (fname.getName().lastIndexOf(".doc") != -1) {
					response.setContentType("application/msword");
				}
				// set for excel file
				else if (fname.getName().lastIndexOf(".xls") != -1) {
					System.out.println("downloadFile 1");
					response.setContentType("application/ms-excel");
				} else if (fname.getName().lastIndexOf(".csv") != -1) {
					response.setContentType("application/ms-excel");
				}
				// set for powerpt file
				else if (fname.getName().lastIndexOf(".ppt") != -1) {
					response.setContentType("application/ms-powerpoint");
				}
				// set for text file
				else if (fname.getName().lastIndexOf(".txt") != -1) {
					response.setContentType("text/plain");
				}
				// set for html file
				else if ((fname.getName().lastIndexOf(".htm") != -1)
						|| (fname.getName().lastIndexOf(".html") != -1)) {
					response.setContentType("text/html");
				}
				// set for rtf file
				else if (fname.getName().lastIndexOf(".rtf") != -1) {
					response.setContentType("text/richtext");
				}
				// set for postscript file
				else if ((fname.getName().lastIndexOf(".ps") != -1)
						|| (fname.getName().lastIndexOf(".ai") != -1)
						|| (fname.getName().lastIndexOf(".eps") != -1)) {
					response.setContentType("application/postscript");
				} else {
					response.setContentType("application/binary");
				}
				System.out.println("downloadFile 2 - fileName: " + fileName);
				response.setHeader("Content-Disposition",
						"attachment; filename=\"" + fileName + "\";");				

				istr = new FileInputStream(fname);
				ostr = response.getOutputStream();
				int curByte = -1;
				while ((curByte = istr.read()) != -1)
					ostr.write(curByte);

				ostr.flush();
			}
		} catch (Exception ex) {
			log.error(ex.getMessage());
			return false;
		} finally {
			try {
				if (istr != null)
					istr.close();
				if (ostr != null)
					ostr.close();
			} catch (Exception ex) {
				log.error("Major Error Releasing Streams: " + ex.toString());
				return false;
			}
		}
		return true;
	}

	/**
	 * Lists all the files in the specified directory and verifies that the
	 * given filename exists.
	 * <p>
	 * Since the file extension is not known, this method will loop through all
	 * the files within the specified directory.
	 * <p>
	 * If the filename is found, the method will return the file path (including
	 * the file name and its extension).
	 * 
	 * @param dir
	 *            The directory path location.
	 * @param fileName
	 *            The name of the file, without the extension.
	 * @return filePath The filepath, including filename and its extension.
	 */
	public static String getFilePath(String dir, String fileName) {
		String filePath = null;

		log.debug("===== Directory to search: " + dir);
		log.debug("===== Filename to search: " + fileName);

		File directory = new File(dir);
		File[] fileList;
		fileList = directory.listFiles();

		log.debug("===== No. of files in directory: " + fileList.length);

		// loop through the list of files within the directory.
		for (int n = 0; n < fileList.length; n++) {
			if (!fileList[n].isDirectory()) {

				if (fileList[n].getName().startsWith(fileName)) {
					filePath = dir + fileList[n].getName();
					log.debug("===== Filename (" + fileName + ") found. ");
				}
			}
		}
		return filePath;
	}

	/**
	 * Returns the file extension.
	 * 
	 * @param filePath
	 *            Location of the file including the file name
	 * @return
	 */
	public static String getFileExtension(String filePath) {
		String extension = null;

		File fname = new File(filePath);

		if (fname != null) {

			// set for tif image
			if ((fname.getName().lastIndexOf(".tif") != -1)
					|| (fname.getName().lastIndexOf(".tiff") != -1)) {
				extension = ".tiff";
			}
			// set for gif image
			else if (fname.getName().lastIndexOf(".gif") != -1) {
				extension = ".gif";
			}
			// set for jpg image
			else if ((fname.getName().lastIndexOf(".jpg") != -1)
					|| (fname.getName().lastIndexOf(".jpeg") != -1)
					|| (fname.getName().lastIndexOf(".jpe") != -1)) {
				extension = ".jpg";
			}
			// set for bmp image
			else if (fname.getName().lastIndexOf(".bmp") != -1) {
				extension = ".bmp";
			}
			// set for png image
			else if (fname.getName().lastIndexOf(".png") != -1) {
				extension = "png";
			}
			// set for pdf file
			else if (fname.getName().lastIndexOf(".pdf") != -1) {
				extension = ".pdf";
			}
			// set for word file
			else if (fname.getName().lastIndexOf(".doc") != -1) {
				extension = ".doc";
			}
			// set for excel file
			else if (fname.getName().lastIndexOf(".xls") != -1) {
				extension = ".xls";
			} else if (fname.getName().lastIndexOf(".csv") != -1) {
				extension = ".csv";
			}
			// set for powerpt file
			else if (fname.getName().lastIndexOf(".ppt") != -1) {
				extension = ".ppt";
			}
			// set for text file
			else if (fname.getName().lastIndexOf(".txt") != -1) {
				extension = ".txt";
			}
			// set for html file
			else if ((fname.getName().lastIndexOf(".htm") != -1)
					|| (fname.getName().lastIndexOf(".html") != -1)) {
				extension = ".html";
			}
			// set for rtf file
			else if (fname.getName().lastIndexOf(".rtf") != -1) {
				extension = ".rtf";
			}
			// set for postscript file
			else if ((fname.getName().lastIndexOf(".ps") != -1)
					|| (fname.getName().lastIndexOf(".ai") != -1)
					|| (fname.getName().lastIndexOf(".eps") != -1)) {
				extension = ".ps";
			}
		}

		return extension;
	}
}
